﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Tool;
using RooHui.OA.Biz.Model;
using RooHui.Infrastructure.Entities.Enum;
using RooHui.Infrastructure.Entities.EFContext;
using RooHui.Infrastructure.Entities;
using System.IO;
using RooHui.Infrastructure.Entities.Repository;

namespace RooHui.OA.Biz
{
    public class ProjectBiz
    {
        /// <summary>
        /// 获取所有项目信息
        /// </summary>
        /// <returns></returns>
        public static List<Project> GetProjectList()
        {
            try
            {
                var projectList = new Project().FindAll();
                return projectList;
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        /// <summary>
        /// 分页获取项目信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static List<Project> GetProjectListByPage(int page, int pageSize, int status, string key, ref int count)
        {
            try
            {
                using (Context ctx = new Context())
                {
                    var expression = from c in ctx.Project
                                     join d in ctx.Product
                                     on c.ProductID equals d.ID
                                     join e in ctx.GuaranteeCompany
                                     on c.GuaranteeCompanyID equals e.ID
                                     join f in ctx.Enterprise
                                     on c.EnterpriseID equals f.ID
                                     join k in ctx.ProjectPolicy
                                     on c.ID equals k.ProjectId
                                     join j in ctx.Policy.Where(m => m.IsAttach == false)
                                     on k.PolicyId equals j.ID
                                     where (c.Status == status || status == -2)
                                     && (c.Status != (int)ProjectStatus.Delete)
                                     && (c.ProjectCode.Contains(key) || c.ProductName.Contains(key) || c.ProjectTitle.Contains(key) || c.ProjectDescription.Contains(key)
                                     || e.CompanyName.Contains(key)
                                     || f.EnterpriseName.Contains(key) || f.EnterpriseCode.Contains(key))
                                     orderby c.CreateTime descending
                                     select new { c, d, e, f, j };
                    count = expression.Count();
                    var data = expression
                        .Skip((page - 1) * pageSize)
                        .Take(pageSize)
                        .ToList().Select(p => new Project().Set(p.c).LoadProduct(p.d).LoadGuaranteeCompany(p.e).LoadEnterprise(p.f).LoadPolicy(p.j)).ToList();
                    return data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        /// <summary>
        /// 根据项目ID获取项目相关资料
        /// </summary>
        /// <param name="projectID"></param>
        /// <returns></returns>
        public static Project GetProjectByID(int projectID)
        {
            try
            {
                using (Context ctx = new Context())
                {
                    var expression = from c in ctx.Project
                                     join d in ctx.Product
                                     on c.ProductID equals d.ID
                                     join e in ctx.GuaranteeCompany
                                     on c.GuaranteeCompanyID equals e.ID
                                     join f in ctx.Enterprise
                                     on c.EnterpriseID equals f.ID
                                     join u in ctx.User
                                     on c.CreateUser equals u.UserName
                                     where c.ID == projectID
                                     orderby c.CreateTime
                                     select new { c, d, e, f, u.RealName };

                    var data = expression.ToList().Select(p => new Project().Set(p.c).LoadProduct(p.d).LoadGuaranteeCompany(p.e).LoadEnterprise(p.f).LoadUser(new U_User() { RealName = p.RealName })).FirstOrDefault();
                    //获取政策信息
                    var policyList = (from c in ctx.Policy
                                      join d in ctx.ProjectPolicy
                                      on c.ID equals d.PolicyId
                                      where d.ProjectId == projectID
                                      select new { c, d })
                                    .ToList()
                                    .Select(p => new Policy().Set(p.c)).ToList();
                    data.PolicyList = policyList;
                    //获取相关资料信息
                    var resourceList = new Resource().FindAll(c => c.Type == (int)ResourceType.ProjectResource && c.RefId == projectID);
                    data.ResourceList = resourceList;
                    return data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        /// <summary>
        /// 增加项目
        /// </summary>
        /// <param name="projectModel"></param>
        /// <returns></returns>
        public static bool ProjectAdd(ProjectModel projectModel)
        {
            try
            {
                var enterprise = new Enterprise()
                {
                    CapitalOperation = projectModel.CapitalOperation,
                    EnterpriceInfo = projectModel.EnterpriceInfo,
                    EnterpriseCode = projectModel.EnterpriseCode,
                    EnterpriseCredit = projectModel.EnterpriseCredit,
                    EnterpriseName = projectModel.EnterpriseName
                };
                // 插入贷款企业信息
                enterprise = enterprise.PostAdd();
                if (enterprise.ID > 0)
                {
                    var project = new Project()
                    {
                        BorrowerName = null,
                        CollateralOpinion = projectModel.CollateralOpinion,
                        CreateTime = DateTime.Now,
                        CreateUser = System.Web.HttpContext.Current.User.Identity.Name,
                        CycleAmount = projectModel.CycleAmount,
                        EnterpriseID = enterprise.ID,
                        Financing = projectModel.Financing,
                        GuaranteeCompanyID = projectModel.GuarCpyID,
                        IncreaseMoney = projectModel.IncreaseMoney,
                        MinInvestment = projectModel.IncreaseMoney,
                        MaxInvestment = projectModel.MaxInvestment,
                        ProductID = projectModel.ProductID,
                        ProductName = projectModel.ProductName,
                        ProjectCode = projectModel.ProjectCode,
                        ProjectDescription = projectModel.ProjectDescription,
                        ProjectTitle = projectModel.ProjectTitle,
                        RiskCotrolSummary = projectModel.RiskCotrolSummary,
                        Status = (ProjectStatus)projectModel.Status,
                        WaitDay = projectModel.WaitDay,
                        GuaranteeRate = projectModel.GuaranteeRate,
                        OriginalRate = projectModel.OriginalRate,

                        BeginDate = DateTime.Now,
                        EndDate = DateTime.Now,
                        ReleaseTime = DateTime.Now,
                        FullScaleTime = DateTime.Now,
                        LendingTime = DateTime.Now,
                        BorrowInterestDate = DateTime.Now
                    };

                    // 插入项目信息
                    project = project.PostAdd();
                    if (project.ID > 0)
                    {
                        var oper = "";
                        ProjectStatus newstatus = ProjectStatus.Save;
                        if (project.Status == ProjectStatus.Save)
                        {
                            oper = "新建项目";
                            newstatus = ProjectStatus.Save;
                        }
                        else if (project.Status == ProjectStatus.Submit)
                        {
                            oper = "提交项目";
                            newstatus = ProjectStatus.Submit;
                        }
                        // 插入项目历史信息
                        var projecthistory = new ProjectHistory()
                        {

                            ChangeContent = oper + project.ProjectTitle,
                            CreateTime = DateTime.Now,
                            CreateUser = System.Web.HttpContext.Current.User.Identity.Name,
                            NewStatus = newstatus,
                            PreState = ProjectStatus.Save,
                            ProjectId = project.ID
                        };
                        projecthistory.PostAdd();

                        // i.e. xx.jpg:yy.png
                        var pathnamelist = projectModel.ProResNames.Split(':');
                        for (int i = 0; i < pathnamelist.Length; i++)
                        {
                            var path = pathnamelist[i].Split(';')[0];
                            var name = pathnamelist[i].Split(';')[1];
                            var extension = Path.GetExtension(path);
                            FileInfo file = new FileInfo(Path.GetFullPath(path));
                            var proResource = new Resource()
                            {
                                CreateTime = DateTime.Now,
                                CreateUser = System.Web.HttpContext.Current.User.Identity.Name,
                                ExtendName = extension,
                                FileSize = "2134", // file.Length.ToString(),
                                Name = name,
                                Path = path,
                                PrivateLevel = PrivateLevel.Public,
                                RefId = project.ID,
                                Type = ResourceType.ProjectResource
                            };
                            proResource.PostAdd();
                        }
                        // 插入项目政策关系信息
                        var policy = new Policy()
                        {
                            BalanceType = (BalanceType)projectModel.BalanceType,
                            CreateTime = DateTime.Now,
                            CreateUser = System.Web.HttpContext.Current.User.Identity.Name,
                            CycleAmount = projectModel.PolicyCycle,
                            Duration = projectModel.Duration,
                            DurationType = (DurationType)projectModel.DurationType,
                            IsAttach = false,
                            PolicyName = projectModel.PolicyName,
                            Rate = projectModel.Rate,
                            SettlementType = (SettlementType)projectModel.SettlementType,
                            Status = (ItemStatus)projectModel.PolicyStatus
                        };
                        policy = policy.PostAdd();

                        if (policy.ID > 0)
                        {
                            var projectpolicy = new ProjectPolicy()
                            {
                                PolicyId = policy.ID,
                                ProjectId = project.ID
                            };
                            projectpolicy = projectpolicy.PostAdd();
                            if (projectpolicy.ID > 0)
                            {
                                var spepoliidlist = projectModel.SpePolicyIDs.Split(':');
                                for (int j = 0; j < spepoliidlist.Length; j++)
                                {
                                    var spepropolicy = new ProjectPolicy()
                                    {
                                        ProjectId = project.ID,
                                        PolicyId = Int32.Parse(spepoliidlist[j])
                                    };
                                    spepropolicy = spepropolicy.PostAdd();
                                }
                                // 启动审批流程
                                bool bStart = ProcessDoingBiz.StartProcess(1, project.ID, 1);
                                if (bStart)
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                return false;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 修改项目
        /// </summary>
        /// <param name="projectModel"></param>
        /// <returns></returns>
        public static bool ProjectEdit(ProjectModel projectModel)
        {
            try
            {
                var project = new Project().Find(projectModel.ProjectID.ToString());
                if (project.ID > 0 && project != null)
                {
                    var enterprise = new Enterprise().Find(project.EnterpriseID.ToString());
                    enterprise.CapitalOperation = projectModel.CapitalOperation;
                    enterprise.EnterpriceInfo = projectModel.EnterpriceInfo;
                    enterprise.EnterpriseCode = projectModel.EnterpriseCode;
                    enterprise.EnterpriseCredit = projectModel.EnterpriseCredit;
                    enterprise.EnterpriseName = projectModel.EnterpriseName;
                    enterprise = enterprise.PostModify();// 更新贷款企业信息
                    if (enterprise.ID > 0 && enterprise != null)
                    {
                        project.BorrowerName = System.Web.HttpContext.Current.User.Identity.Name;
                        project.CollateralOpinion = projectModel.CollateralOpinion;
                        project.CreateTime = DateTime.Now;
                        project.CreateUser = System.Web.HttpContext.Current.User.Identity.Name;
                        project.CycleAmount = projectModel.CycleAmount;
                        project.EnterpriseID = enterprise.ID;
                        project.Financing = projectModel.Financing;
                        project.GuaranteeCompanyID = projectModel.GuarCpyID;
                        project.IncreaseMoney = projectModel.IncreaseMoney;
                        project.MinInvestment = projectModel.IncreaseMoney;
                        project.MaxInvestment = projectModel.MaxInvestment;
                        project.ProductID = projectModel.ProductID;
                        project.ProductName = projectModel.ProductName;
                        project.ProjectCode = projectModel.ProjectCode;
                        project.ProjectDescription = projectModel.ProjectDescription;
                        project.ProjectTitle = projectModel.ProjectTitle;
                        project.RiskCotrolSummary = projectModel.RiskCotrolSummary;
                        project.Status = (ProjectStatus)projectModel.Status;
                        project.WaitDay = projectModel.WaitDay;
                        project.GuaranteeRate = projectModel.GuaranteeRate;
                        project.OriginalRate = projectModel.OriginalRate;

                        project.BeginDate = DateTime.Now;
                        project.EndDate = DateTime.Now;
                        project.ReleaseTime = DateTime.Now;
                        project.FullScaleTime = DateTime.Now;
                        project.LendingTime = DateTime.Now;
                        project.BorrowInterestDate = DateTime.Now;
                        project = project.PostModify(); // 插入项目信息

                        if (project.ID > 0 && project != null)
                        {
                            var oper = "";
                            ProjectStatus newstatus = ProjectStatus.Save;
                            if (project.Status == ProjectStatus.Save)
                            {
                                oper = "修改项目";
                                newstatus = ProjectStatus.Save;
                            }
                            else if (project.Status == ProjectStatus.Submit)
                            {
                                oper = "提交项目";
                                newstatus = ProjectStatus.Submit;
                            }
                            // 插入项目历史信息
                            var projecthistory = new ProjectHistory()
                            {
                                ChangeContent = oper + project.ProjectTitle,
                                CreateTime = DateTime.Now,
                                CreateUser = System.Web.HttpContext.Current.User.Identity.Name,
                                NewStatus = newstatus,
                                PreState = ProjectStatus.Save,
                                ProjectId = project.ID
                            };
                            projecthistory.PostAdd();

                            var resList = ResourceBiz.GetResourceListByProjectID(project.ID);
                            foreach (Resource res in resList)
                            {
                                res.PostDelete();
                            }

                            // i.e. xx.jpg:yy.png
                            var pathnamelist = projectModel.ProResNames.Split(':');
                            for (int i = 0; i < pathnamelist.Length; i++)
                            {
                                var path = pathnamelist[i].Split(';')[0];
                                var name = pathnamelist[i].Split(';')[1];
                                var extension = Path.GetExtension(path);
                                FileInfo file = new FileInfo(Path.GetFullPath(path));
                                var proResource = new Resource()
                                {
                                    CreateTime = DateTime.Now,
                                    CreateUser = System.Web.HttpContext.Current.User.Identity.Name,
                                    ExtendName = extension,
                                    FileSize = "2134", // file.Length.ToString(),
                                    Name = name,
                                    Path = path,
                                    PrivateLevel = PrivateLevel.Public,
                                    RefId = project.ID,
                                    Type = ResourceType.ProjectResource
                                };
                                proResource.PostAdd();
                            }

                            var projpolicy = GetProjPolicyListByProjectID(projectModel.ProjectID);
                            foreach (ProjectPolicy pjply in projpolicy)
                            {
                                var policy = new Policy().Find(pjply.PolicyId.ToString());
                                if (!policy.IsAttach) // 普通策略
                                {
                                    policy.BalanceType = (BalanceType)projectModel.BalanceType;
                                    policy.CreateTime = DateTime.Now;
                                    policy.CreateUser = System.Web.HttpContext.Current.User.Identity.Name;
                                    policy.CycleAmount = projectModel.PolicyCycle;
                                    policy.Duration = projectModel.Duration;
                                    policy.DurationType = (DurationType)projectModel.DurationType;
                                    policy.IsAttach = false;
                                    policy.PolicyName = projectModel.PolicyName;
                                    policy.Rate = projectModel.Rate;
                                    policy.SettlementType = (SettlementType)projectModel.SettlementType;
                                    policy.Status = (ItemStatus)projectModel.PolicyStatus;
                                    policy = policy.PostModify(); // 更新普通策略
                                }
                                else
                                {
                                    pjply.PostDelete(); // 删除项目策略关于表特殊策略
                                }
                            }
                            var spepoliidlist = projectModel.SpePolicyIDs.Split(':');
                            for (int j = 0; j < spepoliidlist.Length; j++)
                            {
                                var prjply = new ProjectPolicy()
                                {
                                    ProjectId = projectModel.ProjectID,
                                    PolicyId = Int32.Parse(spepoliidlist[j])
                                };
                                prjply = prjply.PostAdd(); // 插入项目策略关于表
                            }
                            // 启动审批流程
                            bool bStart = ProcessDoingBiz.StartProcess(1, project.ID, 1);
                            if (bStart)
                            {
                                return true;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 更新项目状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool ProjectStatusChange(int projectId, int destinatStatus)
        {
            try
            {
                var project = new Project().Find(projectId.ToString());
                if (project != null)
                {
                    project.Status = (ProjectStatus)destinatStatus;
                    project = project.PostModify();
                    if (project != null)
                    {
                        var projecthistory = new ProjectHistory();
                        if (project.Status == ProjectStatus.Submit)
                        {
                            projecthistory.ChangeContent = "提交项目:" + project.ProjectTitle;
                            projecthistory.NewStatus = ProjectStatus.Submit;
                        }
                        else if (project.Status == ProjectStatus.Delete)
                        {
                            projecthistory.ChangeContent = "删除项目:" + project.ProjectTitle;
                            projecthistory.NewStatus = ProjectStatus.Delete;
                        }
                        projecthistory.CreateTime = DateTime.Now;
                        projecthistory.CreateUser = System.Web.HttpContext.Current.User.Identity.Name;
                        projecthistory.PreState = (int)ProjectStatus.Save;
                        projecthistory.ProjectId = project.ID;
                        projecthistory.PostAdd(); // 插入项目历史信息

                        if (project.Status == ProjectStatus.Submit)
                        {
                            // 启动审批流程
                            bool bStart = ProcessDoingBiz.StartProcess(1, project.ID, 1);
                            if (bStart)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
                return false;
            }
            return false;
        }

        /// <summary>
        /// 根据项目ID获取项目政策表
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public static List<ProjectPolicy> GetProjPolicyListByProjectID(int projectId)
        {
            try
            {
                using (Context ctx = new Context())
                {
                    var projpolylist = from c in ctx.ProjectPolicy
                                       where c.ProjectId == projectId
                                       orderby c.ID
                                       select c;
                    var data = projpolylist.ToList()
                        .Select(p => new ProjectPolicy().Set(p)).ToList();
                    return data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        /// <summary>
        /// 查询融资进度
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static List<ProjectScheduleModel> LoadProjectSchedules(int page, int pageSize, ref int count)
        {
            using (Context ctx = new Context())
            {
                var query = (from j in ctx.Project
                             join p in ctx.Product
                              on j.ProductID equals p.ID
                             join e in ctx.Enterprise
                              on j.EnterpriseID equals e.ID
                             join g in ctx.GuaranteeCompany
                              on j.GuaranteeCompanyID equals g.ID
                             join it in ctx.Investment
                              on j.ID equals it.ProjectId into ig
                             from i in ig.DefaultIfEmpty()
                             where j.Status == (int)ProjectStatus.Publish || j.Status == (int)ProjectStatus.Full
                             orderby j.ReleaseTime
                             select new
                             {
                                 ProjectId = j.ID,
                                 ProjectTitle = j.ProjectTitle,
                                 ProjectCode = j.ProjectCode,
                                 ProjectStatus = j.Status,
                                 ProductName = p.ProductName,
                                 ProjectReleaseTime = j.ReleaseTime,
                                 EnterpriseName = e.EnterpriseName,
                                 GuaranteeName = g.CompanyName,
                                 GuaranteeLogo = g.LogoImage,
                                 Financing = j.Financing,
                                 InvestAmount = i == null ? 0 : i.InvestMentAmount
                             });
                count = query.GroupBy(c => c.ProjectId).Count();
                return query.GroupBy(c => c.ProjectId)
                       .OrderBy(c=>c.FirstOrDefault().ProjectReleaseTime)
                       .Skip((page - 1)* pageSize)
                       .Take(pageSize)
                       .ToList()
                       .Select(c => new ProjectScheduleModel()
                       {
                           ProjectStatus = (ProjectStatus)c.FirstOrDefault().ProjectStatus,
                           EnterpriseName = c.FirstOrDefault().EnterpriseName,
                           Financing = c.FirstOrDefault().Financing,
                           GuaranteeLogo = c.FirstOrDefault().GuaranteeLogo,
                           GuaranteeName = c.FirstOrDefault().GuaranteeName,
                           ProductName = c.FirstOrDefault().ProductName,
                           ProjectCode = c.FirstOrDefault().ProjectCode,
                           ProjectId = c.FirstOrDefault().ProjectId,
                           ProjectTitle = c.FirstOrDefault().ProjectTitle,
                           Invested = c.Sum(i => i.InvestAmount)
                       })
                       .ToList();
            }
        }
    }
}
